package com.geekhalo.admin.menu;

import com.geekhalo.admin.domain.menu.MenuView;
import com.google.common.collect.Lists;
import lombok.AccessLevel;
import lombok.Getter;

import javax.persistence.Transient;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
public class MenuDTO {
    private Long id;

    private Long parentId;


    private String path;

    private String name;

    private String icon;

    private String component;

//    @Getter(AccessLevel.PRIVATE)
//    private MenuDTO parent;

    private List<MenuDTO> children = Lists.newArrayList();

    private void addChild(MenuDTO menuDTO){
        this.children.add(menuDTO);
//        menuDTO.parent = this;
    }

    public static List<MenuDTO> from(List<MenuView> menuViews) {
        List<MenuDTO> allMenuDTOS = menuViews.stream()
                .map(menuView -> toDTO(menuView))
                .collect(Collectors.toList());

        Map<Long, MenuDTO> idMap = allMenuDTOS.stream()
                .collect(Collectors.toMap(MenuDTO::getId, m -> m));

        allMenuDTOS.forEach(menuDTO -> {
            Long parentId = menuDTO.getParentId();
            if (parentId != null && idMap.containsKey(parentId)){
                idMap.get(parentId).addChild(menuDTO);
            }
        });

        List<MenuDTO> rootMenu = allMenuDTOS.stream()
                .filter(m -> m.getParentId() == null || m.getParentId() == 0)
                .collect(Collectors.toList());

        return rootMenu;
    }

    private static MenuDTO toDTO(MenuView menuView) {
        MenuDTO menuDTO = new MenuDTO();
        menuDTO.id = menuView.getId();
        menuDTO.parentId = menuView.getParentMenuId();
        menuDTO.name = menuView.getName();
        menuDTO.icon = menuView.getIcon();
        menuDTO.component = menuView.getComponent();
        menuDTO.path = menuView.getPath();
        return menuDTO;
    }
}
